package com.lcf.app.swagger.config;

import org.springframework.core.MethodParameter;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局统一拦截返回格式
 */
@ControllerAdvice
public class MyResponseBodyAdvice implements ResponseBodyAdvice {

    protected boolean isStringConverter(Class converterType) {
        return converterType.equals(StringHttpMessageConverter.class);
    }

/*    protected boolean isApiResult(MethodParameter returnType) {
        return returnType.hasMethodAnnotation(ApiResult.class);
    }*/

    //需要过滤swagger相关接口
    protected boolean isSwagger(MethodParameter returnType) {
        return returnType.getDeclaringClass().getName().contains("springfox");
    }

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        //return !isStringConverter(converterType) && isApiResult(returnType);
        return !isStringConverter(converterType) && !isSwagger(returnType);
    }


    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, org.springframework.http.server.ServerHttpRequest request,
                                  ServerHttpResponse response) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", "success");
        if ("void".equals(returnType.getParameterType().getSimpleName()) || body instanceof Map) {
            return body;
        }
        if (body == null) {
            //返回是json个格式类型，无body内容
            return result;
        }
        if (body instanceof Resource) {
            return body;
        }
        result.put("data", body);
        return result;
    }
}
